<template>
  <div class="teaching-projects">
    <div class="page-header">
      <h1>教学项目管理</h1>
      <div class="header-actions">
        <el-input
            v-model="searchText"
            placeholder="搜索项目名称"
            style="width: 200px; margin-right: 16px;"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
        />
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增项目
        </el-button>
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 筛选和表格 -->
    <el-card>
      <div class="filter-bar">
        <el-select v-model="filterStatus" placeholder="项目状态" style="width: 140px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="申报中" value="申报中" />
          <el-option label="已立项" value="已立项" />
          <el-option label="执行中" value="执行中" />
          <el-option label="结题审核中" value="结题审核中" />
          <el-option label="已结题" value="已结题" />
          <el-option label="已驳回" value="已驳回" />
          <el-option label="延期" value="延期" />
          <el-option label="终止" value="终止" />
        </el-select>

        <el-select v-model="filterType" placeholder="项目类型" style="width: 150px; margin-left: 16px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="教改项目" value="教改项目" />
          <el-option label="课程建设项目" value="课程建设项目" />
          <el-option label="教材建设项目" value="教材建设项目" />
          <el-option label="实践教学项目" value="实践教学项目" />
        </el-select>

        <el-select v-model="filterLevel" placeholder="项目级别" style="width: 120px; margin-left: 16px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="国家级" value="国家级" />
          <el-option label="省部级" value="省部级" />
          <el-option label="市厅级" value="市厅级" />
          <el-option label="校级" value="校级" />
        </el-select>

        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="margin-left: 16px;"
            clearable
            @change="handleFilterChange"
        />
      </div>

      <el-table :data="paginatedProjects" stripe v-loading="loading">
        <el-table-column prop="name" label="项目名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="projectType" label="项目类型" width="120" />
        <el-table-column prop="level" label="项目级别" width="100" />
        <el-table-column prop="totalFunding" label="经费总额(万元)" width="140">
          <template #default="{ row }">
            {{ row.totalFunding ? (row.totalFunding / 10000).toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始时间" width="120" />
        <el-table-column prop="endDate" label="结束时间" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="附件" width="100">
          <template #default="{ row }">
            <el-badge :value="row.attachmentCount || 0" :hidden="!row.attachmentCount">
              <el-button type="text" @click="viewAttachments(row)">
                <el-icon><Paperclip /></el-icon>
                附件
              </el-button>
            </el-badge>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" @click="handleEdit(row)" v-if="row.status === '已驳回'">编辑</el-button>
            
            <!-- 状态流转按钮 -->
            <el-button type="text" @click="startExecution(row)" v-if="row.status === '已立项'" style="color: #67c23a;">
              开始执行
            </el-button>
            <el-button type="text" @click="submitFinish(row)" v-if="row.status === '执行中'" style="color: #e6a23c;">
              提交结题
            </el-button>
            
            <el-button type="text" style="color: #f56c6c;" @click="handleDelete(row)" v-if="row.status === '申报中' || row.status === '已驳回'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="showFormDialog"
        :title="isEdit ? '编辑教学项目' : '新增教学项目'"
        width="800px"
        :before-close="handleClose"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入项目名称" />
        </el-form-item>

        <el-form-item label="项目编号" prop="project_number">
          <el-input v-model="formData.project_number" placeholder="留空将自动生成" />
        </el-form-item>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="项目类型" prop="project_type">
              <el-select v-model="formData.project_type" placeholder="请选择" style="width: 100%">
                <el-option label="教改项目" value="教改项目" />
                <el-option label="课程建设项目" value="课程建设项目" />
                <el-option label="教材建设项目" value="教材建设项目" />
                <el-option label="实践教学项目" value="实践教学项目" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目级别" prop="level">
              <el-select v-model="formData.level" placeholder="请选择" style="width: 100%">
                <el-option label="国家级" value="国家级" />
                <el-option label="省部级" value="省部级" />
                <el-option label="市厅级" value="市厅级" />
                <el-option label="校级" value="校级" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="立项日期" prop="approval_date">
              <el-date-picker
                  v-model="formData.approval_date"
                  type="date"
                  placeholder="选择立项日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="立项部门" prop="approval_department">
              <el-input v-model="formData.approval_department" placeholder="请输入立项部门" />
            </el-form-item>
          </el-col>
        </el-row>



        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="start_date">
              <el-date-picker
                  v-model="formData.start_date"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  @change="validateDateRange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="end_date">
              <el-date-picker
                  v-model="formData.end_date"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  @change="validateDateRange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 项目成员管理 -->
        <el-form-item label="项目成员">
          <div class="members-section">
            <el-table :data="formData.members" border size="small" style="margin-bottom: 16px;">
              <el-table-column prop="staffNo" label="工号" min-width="120">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.staffNo"
                    placeholder="请输入工号"
                    @blur="autoFillMemberInfo($index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="姓名" min-width="120">
                <template #default="{ row }">
                  <el-input
                    v-model="row.name"
                    placeholder="姓名"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="department" label="部门" min-width="150">
                <template #default="{ row }">
                  <el-input
                    v-model="row.department"
                    placeholder="部门"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="role" label="角色" min-width="100">
                <template #default="{ row }">
                  <el-select v-model="row.role" placeholder="角色" style="width: 100%">
                    <el-option label="负责人" value="负责人" />
                    <el-option label="成员" value="成员" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button type="text" @click="removeMember($index)" style="color: #f56c6c;">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" plain @click="addMember">
              <el-icon><Plus /></el-icon>
              添加成员
            </el-button>
          </div>
        </el-form-item>

        <!-- 经费信息 -->
        <el-form-item label="经费预算">
          <div class="funding-section">
            <el-table :data="formData.fundings" border size="small" style="margin-bottom: 16px;">
              <el-table-column prop="amount" label="金额(元)" min-width="150">
                <template #default="{ row, $index }">
                  <el-input-number
                    v-model="row.amount"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入金额"
                    @change="validateFundingItem($index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="purpose" label="用途" min-width="200">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.purpose"
                    placeholder="请输入用途"
                    @input="validateFundingItem($index)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button type="text" @click="removeFunding($index)" style="color: #f56c6c;">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" plain @click="addFunding">
              <el-icon><Plus /></el-icon>
              添加经费项
            </el-button>
            <div class="funding-total" v-if="formData.fundings.length > 0">
              <span>经费总计：{{ getTotalFunding().toFixed(2) }} 元</span>
            </div>
          </div>
        </el-form-item>

        <!-- 结题信息（可选，根据项目状态显示） -->
        <div v-if="formData.status === '已结题'" class="finish-info-section">
          <el-divider content-position="left">结题信息</el-divider>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="结题日期" prop="finish_date">
                <el-date-picker
                    v-model="formData.finish_date"
                    type="date"
                    placeholder="选择结题日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结题形式" prop="finish_type">
                <el-select v-model="formData.finish_type" placeholder="请选择" style="width: 100%">
                  <el-option label="评审" value="评审" />
                  <el-option label="验收" value="验收" />
                  <el-option label="自主结题" value="自主结题" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="结题等级" prop="finish_level">
                <el-select v-model="formData.finish_level" placeholder="请选择" style="width: 100%">
                  <el-option label="优秀" value="优秀" />
                  <el-option label="良好" value="良好" />
                  <el-option label="合格" value="合格" />
                  <el-option label="不合格" value="不合格" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结题成果" prop="finish_results">
                <el-input v-model="formData.finish_results" placeholder="报告、论文、教材等" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 文件上传区域 -->
        <el-form-item label="相关附件">
          <div class="upload-section">
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                drag
                :file-list="fileList"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                :before-upload="beforeUpload"
                :auto-upload="false"
                multiple
                accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.rar"
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传申报书、立项书、结题报告等文档<br>
                  支持格式：PDF、DOC、DOCX、PPT、PPTX、XLS、XLSX、TXT、ZIP、RAR<br>
                  单个文件大小不超过 50MB，最多上传 10 个文件
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>



    <!-- 结题提交对话框 -->
    <el-dialog v-model="showFinishDialog" title="提交结题材料" width="600px">
      <el-form :model="finishForm" label-width="100px">
        <el-form-item label="结题日期" required>
          <el-date-picker
              v-model="finishForm.finishDate"
              type="date"
              placeholder="选择结题日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="结题形式" required>
              <el-select v-model="finishForm.finishType" placeholder="请选择" style="width: 100%">
                <el-option label="评审" value="评审" />
                <el-option label="验收" value="验收" />
                <el-option label="自主结题" value="自主结题" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结题等级" required>
              <el-select v-model="finishForm.finishLevel" placeholder="请选择" style="width: 100%">
                <el-option label="优秀" value="优秀" />
                <el-option label="良好" value="良好" />
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="结题成果">
          <el-input
              v-model="finishForm.finishResults"
              type="textarea"
              :rows="3"
              placeholder="请描述结题成果，如：报告、论文、教材、软件等"
          />
        </el-form-item>
        
        <el-form-item label="结题材料">
          <el-upload
              v-model:file-list="finishFileList"
              class="upload-demo"
              drag
              :auto-upload="false"
              multiple
              accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.rar"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将结题材料拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持上传结题报告、研究成果等材料<br>
                支持格式：PDF、DOC、DOCX、PPT、PPTX、XLS、XLSX、TXT、ZIP、RAR
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showFinishDialog = false">取消</el-button>
        <el-button type="primary" :loading="finishLoading" @click="handleFinishSubmit">
          提交结题
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="showViewDialog" title="项目详情" width="800px">
      <div v-if="viewData" class="view-content">
        <el-form label-width="100px" class="view-form">
          <el-form-item label="项目名称">
            <el-input v-model="viewData.name" readonly />
          </el-form-item>

          <el-form-item label="项目编号">
            <el-input v-model="viewData.project_number" readonly />
          </el-form-item>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="项目类型">
                <el-input v-model="viewData.project_type" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目级别">
                <el-input v-model="viewData.level" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="开始时间">
                <el-input v-model="viewData.start_date" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间">
                <el-input v-model="viewData.end_date" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 项目成员 -->
          <el-form-item label="项目成员">
            <el-table :data="viewData.members" border size="small" v-if="viewData.members && viewData.members.length">
              <el-table-column prop="staffNo" label="工号" min-width="120" />
              <el-table-column prop="name" label="姓名" min-width="120" />
              <el-table-column prop="department" label="部门" min-width="150" />
              <el-table-column prop="role" label="角色" min-width="100" />
            </el-table>
            <div v-else class="empty-tip">暂无成员信息</div>
          </el-form-item>

          <!-- 经费信息 -->
          <el-form-item label="经费预算">
            <el-table :data="viewData.fundings" border size="small" v-if="viewData.fundings && viewData.fundings.length">
              <el-table-column prop="amount" label="金额(元)" min-width="150">
                <template #default="{ row }">
                  {{ row.amount ? row.amount.toFixed(2) : '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="purpose" label="用途" min-width="200" />
            </el-table>
            <div v-if="viewData.fundings && viewData.fundings.length" class="funding-total">
              <span>经费总计：{{ viewData.totalFunding ? viewData.totalFunding.toFixed(2) : '0.00' }} 元</span>
            </div>
            <div v-else class="empty-tip">暂无经费信息</div>
          </el-form-item>

          <el-form-item label="项目状态">
            <el-tag :type="getStatusType(viewData.status)">{{ viewData.status }}</el-tag>
          </el-form-item>

          <!-- 审核意见（如果存在） -->
          <el-form-item label="审核意见" v-if="viewData.review_opinion">
            <el-input v-model="viewData.review_opinion" type="textarea" :rows="3" readonly />
          </el-form-item>

          <!-- 结题审核意见（如果存在） -->
          <el-form-item label="结题审核意见" v-if="viewData.finish_review_opinion">
            <el-input v-model="viewData.finish_review_opinion" type="textarea" :rows="3" readonly />
          </el-form-item>

          <!-- 时间信息 -->
          <el-row :gutter="16" v-if="viewData.application_date || viewData.approval_date">
            <el-col :span="12" v-if="viewData.application_date">
              <el-form-item label="申报日期">
                <el-input v-model="viewData.application_date" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="viewData.approval_date">
              <el-form-item label="立项日期">
                <el-input v-model="viewData.approval_date" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 结题信息（如果存在） -->
          <div v-if="viewData.finish_date || viewData.finish_results" class="finish-info-section">
            <el-divider content-position="left">结题信息</el-divider>
            
            <el-row :gutter="16" v-if="viewData.finish_date">
              <el-col :span="12">
                <el-form-item label="结题日期">
                  <el-input v-model="viewData.finish_date" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="viewData.finish_type">
                <el-form-item label="结题形式">
                  <el-input v-model="viewData.finish_type" readonly />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="结题成果" v-if="viewData.finish_results">
              <el-input v-model="viewData.finish_results" type="textarea" :rows="3" readonly />
            </el-form-item>
          </div>

          <!-- 附件列表 -->
          <el-form-item label="项目附件" v-if="viewData.attachments && viewData.attachments.length">
            <el-table :data="viewData.attachments" border size="small">
              <el-table-column prop="file_name" label="文件名" />
              <el-table-column prop="uploaded_at" label="上传时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.uploaded_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row }">
                  <el-button type="text" @click="downloadFile(row)">下载</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="showViewDialog = false">关闭</el-button>
        <el-button type="primary" @click="handleEditFromView" v-if="viewData && (viewData.status === '申报中' || viewData.status === '已驳回')">
          编辑
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Download, UploadFilled, Paperclip } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getTeachingProjects,
  createTeachingProject,
  updateTeachingProject,
  deleteTeachingProject,
  getProjectById,
  uploadProjectAttachment,
  deleteAttachment,
  downloadAttachment
} from '@/api/teachingProject'
import http from '@/utils/request'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const searchText = ref('')
const filterStatus = ref('')
const filterType = ref('')
const filterLevel = ref('')
const dateRange = ref([])
const showFormDialog = ref(false)
const showViewDialog = ref(false)

const showFinishDialog = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const finishLoading = ref(false)
const formRef = ref()
const uploadRef = ref()
const viewData = ref(null)
const fileList = ref([])
const projects = ref([])
const totalCount = ref(0)

// 结题表单
const finishForm = reactive({
  projectId: null,
  finishDate: '',
  finishType: '',
  finishLevel: '',
  finishResults: ''
})

const finishFileList = ref([])

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10
})

// 获取当前用户信息，提供默认值
const getCurrentUserId = () => {
  return userStore.userInfo?.id || 1
}

const currentUserId = getCurrentUserId()

// 前端数据验证函数
const validateFormData = () => {
  const errors = []
  
  // 基本字段验证
  if (!formData.name || formData.name.trim().length < 2) {
    errors.push('项目名称不能少于2个字符')
  }
  
  if (!formData.project_type) {
    errors.push('请选择项目类型')
  }
  
  if (!formData.level) {
    errors.push('请选择项目级别')
  }
  
  if (!formData.start_date) {
    errors.push('请选择项目开始日期')
  }
  
  if (!formData.end_date) {
    errors.push('请选择项目结束日期')
  }
  
  // 申报阶段不限制日期先后顺序，不做跨字段日期先后校验
  
  // 资金数额验证
  if (formData.funding !== null && formData.funding !== undefined && formData.funding !== '') {
    const funding = Number(formData.funding)
    if (isNaN(funding) || funding < 0) {
      errors.push('项目资金必须是非负数字')
    }
    if (funding > 10000000) { // 1000万限制
      errors.push('项目资金金额过大，请检查是否正确')
    }
  }
  
  // 文件验证
  const totalSize = fileList.value.reduce((sum, file) => {
    return sum + (file.size || 0)
  }, 0)
  
  if (totalSize > 100 * 1024 * 1024) { // 100MB总限制
    errors.push('上传文件总大小不能超过100MB')
  }
  
  if (fileList.value.length > 10) {
    errors.push('最多只能上传10个文件')
  }
  
  // 项目成员验证
  if (formData.members && formData.members.length > 20) {
    errors.push('项目成员数量不能超过20人')
  }
  
  formData.members.forEach((member, index) => {
    if (!member.name || member.name.trim().length === 0) {
      errors.push(`第${index + 1}个成员姓名不能为空`)
    }
  })
  
  return errors
}

// 表单数据 - 扩展后的字段
const formData = reactive({
  id: null,
  name: '',
  project_number: '',
  project_type: '',
  level: '',
  leader_id: null,
  fundings: [],  // 替换原来的funding和source
  status: '申报中',
  start_date: '',
  end_date: '',
  application_date: '',
  approval_date: '',
  approval_department: '',
  finish_date: '',
  finish_type: '',
  finish_level: '',
  finish_results: '',
  members: []
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 128, message: '项目名称长度在 2 到 128 个字符', trigger: 'blur' }
  ],
  project_type: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择项目级别', trigger: 'change' }
  ],
  start_date: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_date: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 计算属性 - 分页后的项目（前端分页改为直接使用从后端获取的数据）
const paginatedProjects = computed(() => {
  return projects.value
})

// API调用方法
const fetchProjects = async () => {
  try {
    loading.value = true

    const params = {
      page: pagination.page,
      size: pagination.size,
      search: searchText.value,
      status: filterStatus.value,
      project_type: filterType.value,
      level: filterLevel.value,
      start_date: dateRange.value?.[0]?.split('T')?.[0] || '',
      end_date: dateRange.value?.[1]?.split('T')?.[0] || ''
    }

    const response = await getTeachingProjects(params)
    const list = Array.isArray(response) ? response : (response?.data || [])
    const filtered = list.filter(p => {
      const okName = !searchText.value || (p.name || '').includes(searchText.value)
      const okStatus = !filterStatus.value || p.status === filterStatus.value
      const okType = !filterType.value || p.projectType === filterType.value
      const okLevel = !filterLevel.value || p.level === filterLevel.value
      return okName && okStatus && okType && okLevel
    })
    projects.value = filtered
    totalCount.value = filtered.length

  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 工具方法
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  try {
    const d = typeof dateTimeStr === 'string' || typeof dateTimeStr === 'number' ? new Date(dateTimeStr) : dateTimeStr
    return d ? new Date(d).toLocaleString('zh-CN') : '-'
  } catch {
    return '-'
  }
}

// 规范化日期为 YYYY-MM-DD（无效返回空字符串）
const normalizeDate = (value) => {
  if (!value) return ''
  try {
    const d = new Date(value)
    if (isNaN(d.getTime())) return ''
    return d.toISOString().slice(0, 10)
  } catch {
    return ''
  }
}

const getStatusType = (status) => {
  const types = {
    '申报中': 'info',
    '已立项': 'success',
    '执行中': 'warning',
    '结题审核中': 'warning',
    '已结题': 'success',
    '已驳回': 'danger',
    '延期': 'warning',
    '终止': 'danger'
  }
  return types[status] || 'info'
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    project_number: '',
    project_type: '',
    level: '',
    leader_id: currentUserId,
    leader_name: '',
    fundings: [],
    status: '申报中',
    start_date: '',
    end_date: '',
    application_date: '',
    approval_date: '',
    approval_department: '',
    finish_date: '',
    finish_type: '',
    finish_level: '',
    finish_results: '',
    members: []
  })

  fileList.value = []

  if (formRef.value) {
    formRef.value.resetFields()
  }

  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 成员管理方法
// 经费管理方法
const addFunding = () => {
  formData.fundings.push({
    amount: null,
    purpose: ''
  })
}

const removeFunding = (index) => {
  formData.fundings.splice(index, 1)
  ElMessage.success('经费项删除成功')
}

const validateFundingItem = (index) => {
  const funding = formData.fundings[index]
  if (funding.amount !== null && funding.amount < 0) {
    ElMessage.warning('经费金额不能为负数')
    funding.amount = 0
  }
}

const getTotalFunding = () => {
  return formData.fundings.reduce((total, funding) => {
    return total + (funding.amount || 0)
  }, 0)
}

// 日期验证方法
const validateDateRange = () => {
  if (formData.start_date && formData.end_date) {
    const startDate = new Date(formData.start_date)
    const endDate = new Date(formData.end_date)
    if (startDate >= endDate) {
      ElMessage.warning('开始时间应早于结束时间，请重新选择')
      // 清空结束日期，让用户重新选择
      formData.end_date = ''
    }
  }
}

// 获取负责人姓名
const getLeaderName = () => {
  const leader = formData.members.find(m => m.role === '负责人')
  return leader ? leader.name : ''
}

const addMember = () => {
  formData.members.push({
    staffNo: '',
    name: '',
    department: '',
    userId: null,
    role: '成员'
  })
}

// 工号自动填充成员信息
const autoFillMemberInfo = async (index) => {
  const member = formData.members[index]
  const staffNo = member.staffNo?.trim()
  if (!staffNo) return
  
  try {
    const resp = await http.get('/api/projects/check', { params: { staffNo } })
    const data = resp?.data || resp
    if (data && data.exist) {
      member.name = data.name
      member.department = data.department
      member.userId = data.userId
      ElMessage.success('已自动填充成员信息')
    } else {
      ElMessage.warning('未找到该工号对应的人员，请手动填写')
    }
  } catch (e) {
    ElMessage.warning('查询工号失败，请手动填写')
  }
}

const removeMember = (index) => {
  formData.members.splice(index, 1)
  ElMessage.success('成员删除成功')
}

const handleAdd = () => {
  resetForm()
  // 新增时默认添加一个经费项
  formData.fundings.push({ amount: null, purpose: '' })
  // 新增时默认添加一个成员
  formData.members.push({ staffNo: '', name: '', department: '', userId: null, role: '负责人' })
  // 自动生成项目编号
  generateProjectNumber()
  isEdit.value = false
  showFormDialog.value = true
}

// 生成项目编号
const generateProjectNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
  formData.project_number = `TIP${year}${month}${randomNum}`
}

const handleEdit = async (project) => {
  try {
    loading.value = true

    // 获取完整的项目详情（包含附件）
    const response = await getProjectById(project.id)
    const detail = response?.data || response
    const proj = detail?.project || detail || {}

    resetForm()
    Object.assign(formData, {
      id: proj.id || null,
      name: proj.name || '',
      project_number: proj.projectNumber || '',
      project_type: proj.projectType || '',
      level: proj.level || '',
      leader_id: proj.leaderId || currentUserId,
      fundings: detail?.fundings || [], // 从后端获取的经费列表
      status: proj.status || '申报中',
      start_date: normalizeDate(proj.startDate),
      end_date: normalizeDate(proj.endDate),
      application_date: normalizeDate(proj.applicationDate),
      approval_date: normalizeDate(proj.approvalDate),
      approval_department: proj.approvalDepartment || '',
      finish_date: normalizeDate(proj.finishDate),
      finish_type: proj.finishType || '',
      finish_level: proj.finishLevel || '',
      finish_results: proj.finishResults || '',
      members: (detail?.members || []).map(m => ({
        staffNo: m.staffNo,
        name: m.name,
        department: m.department,
        userId: m.userId,
        role: m.role || '成员'
      }))
    })

    // 设置负责人角色
    const leaderName = detail?.leaderName
    const leaderIndex = formData.members.findIndex(m =>
      (proj.leaderId && m.userId === proj.leaderId) || (leaderName && m.name === leaderName)
    )
    if (leaderIndex !== -1) {
      formData.members[leaderIndex].role = '负责人'
    }

    isEdit.value = true
    showFormDialog.value = true

    // 加载附件列表
    if (detail.attachments && detail.attachments.length > 0) {
      fileList.value = detail.attachments.map(att => ({
        uid: att.id,
        name: att.file_name,
        url: att.file_url,
        status: 'success',
        response: { data: att } // 存储附件信息
      }))
    }

  } catch (error) {
    console.error('获取项目详情失败:', error)
    ElMessage.error('获取项目详情失败')
  } finally {
    loading.value = false
  }
}





const handleView = async (project) => {
  try {
    loading.value = true

    // 获取完整的项目详情
    const response = await getProjectById(project.id)
    const detail = response?.data || response
    const proj = detail?.project || detail || {}
    viewData.value = {
      id: proj.id,
      name: proj.name,
      project_number: proj.projectNumber,
      project_type: proj.projectType,
      level: proj.level,
      totalFunding: detail?.totalFunding || 0,
      status: proj.status,
      start_date: normalizeDate(proj.startDate),
      end_date: normalizeDate(proj.endDate),
      application_date: normalizeDate(proj.applicationDate),
      approval_date: normalizeDate(proj.approvalDate),
      approval_department: proj.approvalDepartment,
      finish_date: normalizeDate(proj.finishDate),
      finish_type: proj.finishType,
      finish_level: proj.finishLevel,
      finish_results: proj.finishResults,
      created_at: proj.createdAt,
      updated_at: proj.updatedAt,
      members: detail?.members || [],
      fundings: detail?.fundings || [],
      attachments: detail?.attachments || [],
      review_opinion: proj.reviewOpinion,
      finish_review_opinion: proj.finishReviewOpinion
    }
    showViewDialog.value = true

  } catch (error) {
    console.error('获取项目详情失败:', error)
    ElMessage.error('获取项目详情失败')
  } finally {
    loading.value = false
  }
}

const handleEditFromView = () => {
  showViewDialog.value = false
  handleEdit(viewData.value)
}

const handleClose = () => {
  showFormDialog.value = false
  resetForm()
}

const beforeUpload = (file) => {
  const isValidSize = file.size <= 50 * 1024 * 1024 // 50MB
  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }

  const fileCount = fileList.value.length
  if (fileCount >= 10) {
    ElMessage.error('最多只能上传 10 个文件!')
    return false
  }

  return false // 阻止自动上传
}

const handleFileChange = (file, newFileList) => {
  fileList.value = newFileList
}

const handleFileRemove = async (file, newFileList) => {
  fileList.value = newFileList

  // 如果是已存在的附件，调用删除API
  if (file.response?.data?.id) {
    try {
      await deleteAttachment(file.response.data.id)
      ElMessage.success('附件删除成功')
    } catch (error) {
      console.error('删除附件失败:', error)
      ElMessage.error('删除附件失败')
    }
  }
}

const handleSubmit = async () => {
  try {
    if (!formRef.value) return
    await formRef.value.validate()

    submitLoading.value = true

    // 前端数据验证
    const validationErrors = validateFormData()
    if (validationErrors.length > 0) {
      ElMessage({
        message: `请检查以下问题：\n${validationErrors.join('\n')}`,
        type: 'warning',
        duration: 8000,
        showClose: true,
        dangerouslyUseHTMLString: false
      })
      return
    }

    // 组装 multipart：data(JSON字符串) + files[]
    const fd = new FormData()
    const payload = {
      name: formData.name,
      projectNumber: formData.project_number,
      projectType: formData.project_type,
      level: formData.level,
      leaderName: getLeaderName(),
      fundings: formData.fundings.filter(f => f.amount !== null && f.amount !== undefined && f.purpose.trim() !== ''),
      startDate: formData.start_date || null,
      endDate: formData.end_date || null,
      applicationDate: formData.application_date || null,
      approvalDate: formData.approval_date || null,
      approvalDepartment: formData.approval_department,
      finishDate: formData.finish_date || null,
      finishType: formData.finish_type,
      finishLevel: formData.finish_level,
      finishResults: formData.finish_results,
      members: formData.members.map(m => ({ staffNo: m.staffNo, name: m.name, department: m.department, role: m.role }))
    }
    fd.append('data', JSON.stringify(payload))
    for (const f of fileList.value) {
      if (f.raw) fd.append('files', f.raw)
    }

    let result
    if (isEdit.value) {
      result = await updateTeachingProject(formData.id, fd)
      ElMessage.success('项目更新成功')
    } else {
      result = await createTeachingProject(fd)
      ElMessage.success('项目创建成功')
    }

    // 如果后端返回具体信息，显示给用户
    if (typeof result === 'string' && result.includes('项目ID')) {
      ElMessage.success(result)
    }

    // 校验负责人
    if (!isEdit.value) {
      // 新增时，如未勾选负责人，默认当前登录用户为负责人
      if (!payload.leaderName || payload.leaderName.trim() === '') {
        payload.leaderName = '' // 交由服务端按当前登录用户兜底
      }
    }

    // 编辑模式附件在同一个 multipart 中上传，无需二次上传

    showFormDialog.value = false
    resetForm()
    await fetchProjects() // 重新加载数据

  } catch (error) {
    console.error('提交失败:', error)
    
    // 详细的错误处理
    let errorMessage = '操作失败'
    
    if (error.response) {
      const { status, data } = error.response
      
      // 根据HTTP状态码提供具体的错误信息
      switch (status) {
        case 400:
          if (data && typeof data === 'string') {
            errorMessage = `请求参数错误：${data}`
          } else if (data && data.message) {
            errorMessage = `请求参数错误：${data.message}`
          } else {
            errorMessage = '请求参数错误，请检查填写的信息是否正确'
          }
          break
          
        case 401:
          // 401 交由全局拦截器处理（弹出“登录状态已过期”对话框并跳转登录），这里不再重复提示
          return
          
        case 403:
          errorMessage = '权限不足，无法执行此操作'
          break
          
        case 413:
          errorMessage = '上传文件过大，请检查文件大小限制'
          break
          
        case 422:
          errorMessage = '数据验证失败，请检查必填字段和数据格式'
          break
          
        case 500:
          if (data && typeof data === 'string') {
            // 处理后端RuntimeException返回的错误信息
            if (data.includes('负责人不存在')) {
              errorMessage = '系统错误：负责人信息异常，请联系管理员'
            } else if (data.includes('当前用户不存在')) {
              errorMessage = '用户认证异常，请重新登录'
            } else if (data.includes('未登录或认证信息丢失')) {
              errorMessage = '登录状态异常，请重新登录'
            } else if (data.includes('日期')) {
              errorMessage = '日期格式错误，请检查日期输入'
            } else {
              errorMessage = `服务器错误：${data}`
            }
          } else {
            errorMessage = '服务器内部错误，请稍后重试或联系管理员'
          }
          break
          
        default:
          errorMessage = `网络错误 (${status})，请稍后重试`
      }
    } else if (error.code === 'ECONNABORTED') {
      errorMessage = '请求超时，请检查网络连接或稍后重试'
    } else if (error.message && error.message.includes('Network Error')) {
      errorMessage = '网络连接异常，请检查网络设置'
    } else if (error.message) {
      errorMessage = `操作失败：${error.message}`
    }
    
    // 显示错误信息，使用warning类型让用户更容易注意到
    if (errorMessage) {
      ElMessage({
        message: errorMessage,
        type: 'warning',
        duration: 8000, // 延长显示时间，让用户有足够时间阅读
        showClose: true
      })
    }
    
    // 不要关闭对话框，让用户可以修正问题后重新提交
    
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = async (project) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除项目"${project.name}"吗？此操作将同时删除相关附件。`,
        '确认删除',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await deleteTeachingProject(project.id)
    ElMessage.success('删除成功')
    await fetchProjects() // 重新加载数据

  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const viewAttachments = (project) => {
  if (project.attachment_count > 0) {
    ElMessage.info(`该项目共有 ${project.attachment_count} 个附件，请点击"查看"查看详情`)
  } else {
    ElMessage.info('该项目暂无附件')
  }
}

const downloadFile = async (attachment) => {
  try {
    await downloadAttachment(attachment.id, attachment.file_name)
    ElMessage.success(`开始下载文件: ${attachment.file_name}`)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

const exportData = async () => {
  const { exportData: exportUtil } = await import('@/utils/exportUtils')
  
  const filters = {
    search: searchText.value,
    status: filterStatus.value,
    type: filterType.value,
    level: filterLevel.value
  }
  
  await exportUtil('teaching-projects', filters, '教学项目列表.xlsx')
}

const handleSearch = () => {
  pagination.page = 1
  fetchProjects()
}

const handleFilterChange = () => {
  pagination.page = 1
  fetchProjects()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchProjects()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchProjects()
}

// 状态流转方法
const startExecution = async (project) => {
  try {
    await ElMessageBox.confirm(
      `确定要开始执行项目"${project.name}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await http.post(`/api/projects/${project.id}/start-execution`)
    ElMessage.success('项目已开始执行')
    await fetchProjects() // 重新加载数据

  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始执行失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const submitFinish = (project) => {
  finishForm.projectId = project.id
  Object.assign(finishForm, {
    finishDate: '',
    finishType: '',
    finishLevel: '',
    finishResults: ''
  })
  finishFileList.value = []
  showFinishDialog.value = true
}

const handleFinishSubmit = async () => {
  try {
    if (!finishForm.finishDate || !finishForm.finishType || !finishForm.finishLevel) {
      ElMessage.warning('请填写完整的结题信息')
      return
    }

    finishLoading.value = true

    // 组装结题数据
    const fd = new FormData()
    const finishData = {
      finishDate: finishForm.finishDate,
      finishType: finishForm.finishType,
      finishLevel: finishForm.finishLevel,
      finishResults: finishForm.finishResults
    }
    fd.append('data', JSON.stringify(finishData))
    
    // 添加结题材料文件
    for (const f of finishFileList.value) {
      if (f.raw) fd.append('files', f.raw)
    }

    await http.post(`/api/projects/${finishForm.projectId}/finish`, fd)
    ElMessage.success('结题申请已提交，等待审核')
    showFinishDialog.value = false
    await fetchProjects() // 重新加载数据

  } catch (error) {
    console.error('提交结题失败:', error)
    ElMessage.error('提交失败')
  } finally {
    finishLoading.value = false
  }
}

onMounted(() => {
  fetchProjects()
})
</script>

<style scoped>
.teaching-projects {
  max-width: 1400px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  align-items: center;
}

.filter-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.view-content {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-top: 16px;
}

.detail-section h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.upload-section {
  width: 100%;
}

.upload-demo {
  margin-bottom: 16px;
}

.el-upload__tip {
  line-height: 1.4;
  color: #999;
}

.funding-section {
  width: 100%;
}

.funding-total {
  margin-top: 8px;
  text-align: right;
  font-weight: bold;
  color: #409eff;
}

.view-form .el-input.is-disabled .el-input__inner,
.view-form .el-textarea.is-disabled .el-textarea__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 20px;
  background-color: #f9f9f9;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: space-between;
  }

  .filter-bar {
    flex-wrap: wrap;
    gap: 8px;
  }

  .filter-bar > * {
    margin-left: 0 !important;
  }
}
</style>